--[[

	数据操作代理

--]]

local cjson = require("cjson")
local table_insert = table.insert
local table_remove = table.remove



local M = class("DataProxy")

function M:ctor()



    self.redis_key = {
        user_token = "user_token",
        user_pos = "user_pos", --aid: 节点名
        match_pos = "match_pos",
        table_money = "table_money", --桌子带入
        node_tables = "node_tables", --节点所建桌子
        ban_user = "ban_user", --封号
        room_user_num = "room_user_num", --房间用户人数
        member_profile_info = "member_profile_info", --个人信息
        member_game_info = "member_game_info", --货币信息
        mtt = "mtt", --比赛信息
        texas_match_sign_up = "sign:mtt", --比赛报名表
        member_card_info = "member_card_info", --最好牌记录
        texas_jackpot = "texas_jackpot",
        mtt_all = "mtt:all",
        m_info_key_mid = "m_info_key_mid",
        mtt_user = "mtt:user",

    }

    self.key_room_user_num = self.redis_key.room_user_num --房间用户人数
    self.key_user_info = self.redis_key.m_info_key_mid --个人信息
    self.key_user_money = self.redis_key.m_info_key_mid --货币信息
    self.key_texas_match = "mtt" --比赛信息
    self.key_texas_mtt_match = "mtt_all" --德州比赛
    self.key_texas_match_sign_up = "texas_match_sign_up" --比赛报名表
    self.key_member_card_info = self.redis_key.m_info_key_mid --最好牌记录
    self.key_texas_jackpot = self.redis_key.texas_jackpot
    self.m_info_key_mid = self.redis_key.m_info_key_mid

    self.queue_name = "logs_game"

    self.logs_table_num = 0 --记录的条数

    self:register()
end

--热更会自动调用
function M:register()
end

---------------------------------------------------------------------------------------------------------------------------
--redis
---------------------------------------------------------------------------------------------------------------------------
--根据uid 与 name 取key
function M:getRedisKey(name, key1, key2)
    if not self.redis_key[name] then
        g.log:err("getRediskey err!", name, key1)
        return nil
    end
    local key = self.redis_key[name]
    if key1 then
        key = self.redis_key[name]..":"..key1
    end
    if key2 then
        key = self.redis_key[name]..":"..key2
    end

    return key

    --local key = g.const:getRedisKey(name, uid)
    --if not key then
    --    g.log:err("getRediskey err!", name, uid)
    --    return
    --end
    --return key
end

--获取玩家所在节点位置
function M:getUserPos(uid)
    local key = self:getRedisKey(self.redis_key.user_pos, uid)
    local res = g.callRedis("get", key)
    if not res then
        return
    end
    local nn, addr = string.match(res, "([^:].+):(%w+)$")
    if not (nn and addr) then
        g.log:err("get_user_pos failed, ac=%s res=%s", uid, res)
        return
    end
    return {nodefullname = nn, address = addr}
end

--删除玩家所在节点位置
function M:removeUserPos(uid)
    local key = self:getRedisKey(self.redis_key.user_pos, uid)
    return g.callRedis("del", key)
end

--记录用户所在节点，存到redis各个节点共享
function M:setUserPos(uid, address)
    local key = self:getRedisKey(self.redis_key.user_pos, uid)
    local pos = string.format("%s:%08x", g.nodefullname, address) --在clusert.service里有设置
    local ex = g.const.redis_ex.common
    g.sendRedis("setex", key, ex, pos)
    return true
end

function M:getMatchPos(rid)
    local key = self:getRedisKey(self.redis_key.match_pos, rid)
    local res = g.callRedis("get", key)
    if not res then
        return
    end
    local nn, addr = string.match(res, "([^:].+):(%w+)$")
    if not (nn and addr) then
        g.log:err("get_match_pos failed, ac=%s res=%s", rid, res)
        return
    end
    return {nodefullname = nn, address = addr}
end

--记录普通场买入桌子金币， 如果节点挂了可以自动恢复返回金币到用户
function M:setTableUserMoney(msg)
    local tid = msg.tid
    local uid = msg.uid
    local str = cjson.encode(msg.moneys)
    local key = self:getRedisKey(self.redis_key.table_money, tid)
    --g.log:debug("1111112222",  uid, str)
    return g.callRedis("hmset", key, uid, str)
end

function M:getTableUsers(tid)
    local key = self:getRedisKey(self.redis_key.table_money, tid)
    local res =  g.callRedis("hgetall", key)
    local data = redis_to_table(res)
    return data
end

--function M:getTableUserMoney(tid, uid)
--    local key = self:getRedisKey(self.redis_key.table_money, tid)
--    return g.callRedis("hmget", key, uid)
--end

function M:delTableUserMoney(tid, uid)
    local key = self:getRedisKey(self.redis_key.table_money, tid)
    return g.callRedis("hdel", key, uid)
end

function M:setTables(tid)
    local key = self:getRedisKey(self.redis_key.node_tables)
    local node_name = key .. g.getNodeId()
    return g.sendRedis("LPUSH", node_name, tid)
end

function M:delTables(tid)
    local key = self:getRedisKey(self.redis_key.node_tables)
    local node_name = key .. g.getNodeId()
    g.sendRedis("LREM", node_name, 0, tid)
    self:delLogsTable(tid)

    return true
end

function M:getTables()
    local key = self:getRedisKey(self.redis_key.node_tables)
    local node_name = key .. g.getNodeId()
    return g.callRedis("LRANGE", node_name, 0, -1)
end


function M:setBanUser(uid)
    local key = self:getRedisKey(self.redis_key.ban_user, uid)
    local data = string.format("%s", uid)
    local ex = g.const.redis_ex.ban_user
    g.sendRedis("setex", key, ex, data)
end

function M:getBanUser(uid)
    local key = self:getRedisKey(self.redis_key.ban_user, uid)
    local res = g.callRedis("get", key)
    if not res then
        return
    end
    return res
end





---------------------------------------------------------------------------------------------------------------------------
--mysql
---------------------------------------------------------------------------------------------------------------------------

--读取普通房间配置
function M:getRoomConfig()
    --local data = g.callMysql("select * from texas_room_group")
    --local tb = {}
    --for _, v in pairs(data) do
    --    tb[v.id] = v
    --end
    --return tb

    local tb = require("config.texas_room_group")
    --g.log:debug("getRoomConfig:", tb)
    return tb

end

--更新房间在线人数
function M:updateRoomUserNum(rid, data)
    --local sql = string.format("update texas_room_group set user_count='%s' where id='%d' limit 1", user_count, rid)
    --g.sendMysql(sql)
    --local key = self:getRedisKey(self.key_room_user_num, rid)
    local key = self.key_room_user_num
    --local ex = g.const.redis_ex.common
    --g.sendRedis("setex", key, ex, user_count)
    local v = cjson.encode(data)
    g.sendRedis("hset", key, rid, v)
    --g.sendRedis("expire", key, ex)
end


--读取比赛盲注配置
function M:getBlindConfig()
    --local data = g.callMysql("select * from texas_match_blind_cfg")
    local data = require("config.texas_match_blind_cfg")
    local tb = {}
    for k, v in pairs(data) do
        if not tb[v.bid] then
            tb[v.bid] = {}
        end
        tb[v.bid][v.id] = v
    end
    return tb

end



--读用户信息
function M:getUserInfo(uid)
    --local sql = string.format("select * from member_profile_info where mid=%d limit 1", uid)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data[1]
    --end
    --return nil

    local key = self:getRedisKey(self.redis_key.m_info_key_mid, uid)
    local res = g.callRedis("hgetall", key)
    --g.log:debug("data:",res, key)
    if not res then
        return
    end
    local data = redis_to_table(res)

    data.bonus = tonumber(data.bonus)
    data.mid = tonumber(data.mid)
    data.status = tonumber(data.status)
    data.gmoney = tonumber(data.gmoney)
    data.mactived = tonumber(data.mactived) --登录时间
    data.ts = tonumber(data.ts)
    data.chips = tonumber(data.chips)
    data.lrstatus = tonumber(data.lrstatus)
    data.winning = tonumber(data.winning)
    data.mcreated = tonumber(data.mcreated)
    data.ex_time = tonumber(data.ex_time)
    data.login_times = tonumber(data.login_times)
    data.series_times = tonumber(data.series_times)
    data.lsrc = tonumber(data.lsrc)
    data.type_card = tonumber(data.type_card)
    data.best_card_rank = tonumber(data.best_card_rank or 10000)

    data.pfr_num = tonumber(data.pfr_num or 0) --翻牌数
    data.pfr_raise_num = tonumber(data.pfr_raise_num or 0) --翻前加注数
    data.wsd_total = tonumber(data.wsd_total or 0) --摊牌数
    data.wsd_win_num = tonumber(data.wsd_win_num or 0) --摊牌胜
    data.round_total = tonumber(data.round_total or 0) --总局数
    data.vpip_num = tonumber(data.vpip_num or 0) --入局数
    data.win_num = tonumber(data.win_num or 0) --胜局
    data.fold_total = tonumber(data.fold_total or 0) --弃牌局数
    data.fold_pre = tonumber(data.fold_pre or 0) --翻牌前弃牌局数
    data.fold_flop = tonumber(data.fold_flop or 0) --翻牌弃牌局数
    data.fold_turn = tonumber(data.fold_turn or 0) --转牌弃牌局数
    data.fold_river = tonumber(data.fold_river or 0) --河牌弃牌局数
    data.max_win_chips = tonumber(data.max_win_chips or 0) --最大赢钱数

    data.tables = data.tables or "{}"
    data.tables = cjson.decode(data.tables) --是否还在桌子里有金币



    return data
end

function M:setUserExTime(uid)
    local key = self:getRedisKey(self.redis_key.m_info_key_mid, uid)
    g.sendRedis("hset", key, "ex_time", g.time())
end

--更新玩家token时间
function M:setUserExTimeSet(uid)
    if uid < g.const.robot.max_mid then
        --机器人
        return
    end
    local key = "user_zset"
    g.sendRedis("zadd", key, g.time(), uid)
end

--玩家筹码
function M:getUserChip(uid)
    --local sql = string.format("select chips from member_game_info where mid=%d limit 1", uid)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data[1].chips
    --end
    --return nil

    local key = self:getRedisKey(self.redis_key.m_info_key_mid, uid)
    local res = g.callRedis("hget", key, "chips")
    --g.log:debug("data:", res)
    if not res then
        return
    end
    return math.floor(tonumber(res))

end

--保存玩家筹码
function M:setUserChip(uid, chips)
    --local sql = string.format("update member_game_info set chips=`chips` + '%s' where mid=%d limit 1", chips, uid)
    --local data = g.callMysql(sql)
    ----print("#####setUserChip#####", tostring(data))
    --if data and next(data) and data.affected_rows and data.affected_rows > 0 then
    --    return true
    --end
    --return nil
    chips = math.floor(chips)
    local key = self:getRedisKey(self.key_user_money, uid)
    g.callRedis("hset", key, "chips", chips)
    return true

end

function M:getUserMoney(uid)
    --local sql = string.format("select * from member_game_info where mid=%d limit 1", uid)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data[1]
    --end
    --return nil


    --local key = self:getRedisKey(self.key_user_money, uid)
    --local res = g.callRedis("hgetall", key)
    --g.log:debug("data:",res)
    --if not res then
    --    return
    --end
    --local data = redis_to_table(res)
    --for k, v in pairs(data) do
    --    data[k] = tonumber(v)
    --end
    --return data

    local info =  self:getUserInfo(uid)
    local money = {winning = info.winning, bonus = info.bonus, chips = info.chips, gmoney = info.gmoney}
    return money
end

--保存玩家金币
function M:addUserMoney(uid, moneys)
    local chips = moneys.chips or 0
    local bonus = moneys.bonus or 0
    local winning = moneys.winning or 0
    local gmoney = moneys.gmoney or 0
    if chips == 0 and bonus == 0 and winning == 0 and gmoney == 0 then
        --如果都没有发生变化就不写入记录了。
        return
    end

    --local sql = string.format("update member_game_info set chips=`chips` + '%s', bonus=`bonus` + '%s', winning=`winning` + '%s', gmoney=`gmoney` + '%s'  where mid=%d limit 1",
    --        chips, bonus, winning, gmoney, uid)
    --local data = g.callMysql(sql)
    ----print("#####addUserMoney#####", tostring(data))
    --if data and next(data) and data.affected_rows and data.affected_rows > 0 then
    --    return true
    --end
    --return nil

    local key = self:getRedisKey(self.key_user_money, uid)
    local data = self:getUserMoney(uid)
    if chips ~= 0 then
        data.chips = math.floor(data.chips + chips)
        g.callRedis("hset", key, "chips", data.chips)
    end
    if bonus ~= 0 then
        data.bonus = math.floor(data.bonus + bonus)
        g.callRedis("hset", key, "bonus", data.bonus)
    end
    if winning ~= 0 then
        data.winning = math.floor(data.winning + winning)
        g.callRedis("hset", key, "winning", data.winning)
    end
    if gmoney ~= 0 then
        data.gmoney = math.floor(data.gmoney + gmoney)
        g.callRedis("hset", key, "gmoney", data.gmoney)
    end
    return true
end

function M:subUserMoney(uid, moneys)
    local chips = moneys.chips
    local bonus = moneys.bonus
    local winning = moneys.winning
    local gmoney = moneys.gmoney
    --local sql = string.format("update member_game_info set chips=`chips` - '%s', bonus=`bonus` - '%s', winning=`winning` - '%s', gmoney=`gmoney` - '%s'  where mid=%d limit 1",
    --        chips, bonus, winning, gmoney, uid)
    --local data = g.callMysql(sql)
    ----print("#####subUserMoney#####", tostring(data))
    --if data and next(data) and data.affected_rows and data.affected_rows > 0 then
    --    return true
    --end
    --return nil

    local key = self:getRedisKey(self.key_user_money, uid)
    local data = self:getUserMoney(uid)
    if chips ~= 0 then
        data.chips = math.floor(data.chips - chips)
        g.callRedis("hset", key, "chips", data.chips)
    end
    if bonus ~= 0 then
        data.bonus = math.floor(data.bonus - bonus)
        g.callRedis("hset", key, "bonus", data.bonus)
    end
    if winning ~= 0 then
        data.winning = math.floor(data.winning - winning)
        g.callRedis("hset", key, "winning", data.winning)
    end
    if gmoney ~= 0 then
        data.gmoney = math.floor(data.gmoney - gmoney)
        g.callRedis("hset", key, "gmoney", data.gmoney)
    end
    return true
end

--玩家所在桌子持有金币
function M:setUserTableChips(uid, data)
    --local key = "user_tables:"..uid
    --g.callRedis("hset", key, data.tid, data.chips)
    --local ex = g.const.redis_ex.seven_day
    --g.sendRedis("setex", key..":"..data.tid, ex)

    local key = self:getRedisKey(self.key_user_info, uid)
    local res = g.callRedis("hget", key, "tables")
    if not res then
        res = "{}"
    end
    res = cjson.decode(res)
    local tid = data.tid
    local chip = data.chip
    res[tid] = chip
    if chip == 0 then
        res[tid] = nil
    end
    g.sendRedis("hset", key, "tables", cjson.encode(res))
end

function M:getUserTableChips(uid)
    --local key = "user_tables:"..uid
    --local res = g.callRedis("hgetall", key)
    --if not res then
    --    return
    --end
    --local data = redis_to_table(res)
    --self:getUserInfo()

    local key = self:getRedisKey(self.key_user_info, uid)
    local res = g.callRedis("hget", key, "tables")
    if not res then
        res = "{}"
    end
    res = cjson.decode(res)
    --g.log:debug("getUserTableChips:",uid, res)
    return res
end

function M:delUserTableChips(uid)
    local key = self:getRedisKey(self.key_user_info, uid)
    local res = {}
    g.sendRedis("hset", key, "tables", cjson.encode(res))
end


--玩家个人信息记录
function M:setUserTexasOver(uid, msg)
    local key = self:getRedisKey(self.key_user_money, uid)
    local data = self:getUserInfo(uid)
    local tb = {}
    if msg.pfr_num then
        tb.pfr_num = data.pfr_num + 1 --翻牌数
    end
    if msg.pfr_raise_num then
        tb.pfr_raise_num = data.pfr_raise_num + 1 --翻牌数
    end
    if msg.wsd_total then
        tb.wsd_total = data.wsd_total + 1 --摊牌数
    end
    if msg.wsd_win_num then
        tb.wsd_win_num = data.wsd_win_num + 1 --摊牌胜
    end
    if msg.round_total then
        tb.round_total = data.round_total + 1 --总局数
    end
    if msg.vpip_num then
        tb.vpip_num = data.vpip_num + 1 --入局数
    end
    if msg.win_num then
        if msg.win_num > 0 then
            tb.win_num = data.win_num + 1 --胜局
            if data.max_win_chips < msg.win_num  then
                tb.max_win_chips = msg.win_num --最大赢钱数
            end
        end
    end
    if msg.fold_total then
        tb.fold_total = data.fold_total + 1 --弃牌局数
    end
    if msg.fold_pre then
        tb.fold_pre = data.fold_pre + 1 --翻牌前弃牌局数
    end
    if msg.fold_flop then
        tb.fold_flop = data.fold_flop + 1 --翻牌弃牌局数
    end
    if msg.fold_turn then
        tb.fold_turn = data.fold_turn + 1 --转牌弃牌局数
    end
    if msg.fold_river then
        tb.fold_river = data.fold_river + 1 --河牌弃牌局数
    end

    local function unpack(tb)
        local t = {}
        for k, v in pairs(tb) do
            table_insert(t, k)
            table_insert(t, v)
        end
        return table.unpack(t)
    end
    g.sendRedis("hset", key, unpack(tb))
end

--比赛状态
function M:setMatchRoomStatus(rid, state, end_time)
    --local sql = string.format("update texas_match set status=%d where id=%d limit 1", state, rid)
    --if end_time then
    --    sql = string.format("update texas_match set status=%d, end_time=%d where id=%d limit 1", state, end_time, rid)
    --end
    --local data = g.callMysql(sql)
    --if data and next(data) and data.affected_rows and data.affected_rows > 0 then
    --    return true
    --end
    --return nil

    local key = self:getRedisKey(self.key_texas_match, rid)
    g.callRedis("hset", key, "status", state)
    if end_time then
        g.callRedis("hset", key, "end_time", end_time)
    end

    local key = self:getRedisKey(self.key_texas_mtt_match)
    local data = g.callRedis("hget", key, "mtt:"..rid)
    if data and string.len(data) > 3 then
        data = cjson.decode(data)
        data.status = state
        if end_time then
            data.end_time = g.time()
        end
        g.callRedis("hset", key, "mtt:"..rid, cjson.encode(data))
    else
        g.log:warn("no key setMatchRoomStatus:", key, rid, data)
    end
end

--比赛场信息
function M:getMatchRoom(rid)
    --local sql = string.format("select * from texas_match where id=%d limit 1", rid)
    --local data = g.callMysql(sql)
    ----print("#####getMatchRoom#####", tostring(data))
    --if data and next(data) then
    --    return data[1]
    --end
    --return nil
    rid = math.floor(rid)
    local key = self:getRedisKey(self.key_texas_match, rid)
    --g.log:info("getMatchRoom:", key)
    local res = g.callRedis("hgetall", key)
    if not res then
        return
    end
    local data = redis_to_table(res)
    local tb = {
        "id","blind_level","status","seat_count","start_time","type","small_blind","min_player","cost","repurchase","end_time",
        "pool","bid","reward_pool","delay_time","mid","chips","max_player","sign_count","fee",
    }
    for _, v in pairs(tb) do
        data[v] = tonumber(data[v])
    end
    --g.log:info("getMatchRoom:", data)

    return data

end

--玩家是否报名了比赛
function M:getMatchSign(rid, uid)
    --local sql = string.format("select * from texas_match_sign_up where rid=%d and mid=%d and status=1 limit 1", rid, uid)
    --local data = g.callMysql(sql)
    ----print("#####getMatchSign#####", tostring(data))
    --if data and next(data) then
    --    return data[1]
    --end
    --return nil

    local key = self:getRedisKey(self.key_texas_match_sign_up, rid)
    local res = g.callRedis("sismember", key, uid)

    return res
end

--玩家现在报名了多少个比赛
function M:getUserMatchSign(uid)
    --local sql = string.format("select * from texas_match_sign_up where mid=%d and status=1", uid)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data
    --end
    --return nil

    local key = self:getRedisKey(self.key_texas_match_sign_up, uid)
    local res = g.callRedis("hgetall", key)
    if not res then
        return
    end
    local data = redis_to_table(res)
    return data

end

--比赛场升盲
function M:setMatchBlindLevel(rid, level)
    --local sql = string.format("update texas_match set blind_level=%d where id=%d limit 1", level, rid)
    --g.sendMysql(sql)

    local key = self:getRedisKey(self.key_texas_match, rid)
    g.callRedis("hset", key, "blind_level", level)

end

--金币流水日志
--mode 来源id const.chip中定义
--actFlag 0流出 1流入
--chips 变化值
--user_chips 最终值
--remark 牌局id
--desc 描述
function M:setLogsChip(msg)
    if msg.mid == 0 then return  end
    --local mid = msg.mid
    --local mode = msg.mode
    --local remark = msg.remark
    --local desc = msg.desc or ""
    --
    --local flag = msg.flag --增加或减少的标记
    --local alter_value = msg.alter_value
    --local current_value = msg.current_value
    --local tid = msg.tid or ""
    --local ltype = msg.ltype --金币类型 1:chips 2:bonus 3:winning
    --local game_type = msg.game_type
    --local ltime = msg.ltime
    --local sql = string.format("insert delayed into logs_chips set `mid` = '%d', `lmode` = '%d', "..
    --        "`lflag` = '%d', `alter_value` = '%s',  `lremark` = '%d', `ldesc` = '%s', `ltime` = '%d', "..
    --        "`tid`='%s',`current_value` = '%s', `game_type`='%s', `ltype`='%s'",
    --        mid, mode, flag, alter_value,  remark, desc, ltime, tid, current_value, game_type, ltype)
    --g.sendMysql(sql)


    g.sendRabbitQueue(msg, self.queue_name)
    return true
end

--桌子中金币流水日志
function M:setLogsDeskChip(msg)
    --lid 牌局id
    --mid 玩家id
    --rid 房间id
    --seatid 座位id
    --win 输赢值
    --chipin 买入
    --cards 手牌
    --fee 税
    --seat_chips 桌子上金币
    --user_chips 总金币
    --mix_win
    --mix_rate
    --is_win 0输 1赢
    --is_vpip
    --pfr 翻牌: 1 / 加注翻牌 : 2
    --wsd
    --wtsd
    --fold
    --created
    local lid = msg.lid
    local mid = msg.mid
    local rid = msg.rid
    if not lid or not mid or not rid then
        g.log:err("setLogsDeskChip:", msg)
        return
    end
    --local seatid = msg.seatid or 0
    --local win = msg.win or 0
    --local chipin = msg.chipin or 0
    --local cards = msg.cards or ""
    --local fee = msg.fee or 0
    --local seat_chips = msg.seat_chips or 0
    --local user_chips = msg.user_chips or 0
    --local is_win = msg.is_win or 0
    --local is_vpip = msg.is_vpip or 0
    --local pfr = msg.pfr or 0
    --local wsd = msg.wsd or 0
    --local wtsd = msg.wtsd or 0
    --local fold = msg.fold or 0
    --local tid = msg.tid or ""
    --local sb = msg.sb or 0
    --local bb = msg.bb or 0
    local is_match = msg.is_match
    local is_robot = msg.is_robot
    local table_name = "texas_logs_table_chips"
    if is_match then
        table_name = "texas_logs_table_chips_mtt"
    end
    if is_robot then
        table_name = "texas_logs_table_chips_bot"
    end
    msg.cmd = table_name
    msg.created = msg.created or g.time()
    if msg.is_robot then
        msg.is_robot = 1
    else
        msg.is_robot = 0
    end
    --local sql = string.format("insert delayed into %s set `lid` = '%d',`mid` = '%d', `rid`='%d', `seatid` = '%d', "..
    --        "`win` = '%d', `chipin` = '%s', `cards` = '%s', `fee` = '%d', `seat_chips` = '%d', `user_chips` = '%d', `tid`='%s', "..
    --        "`is_win`='%d', `is_vpip`='%d', `pfr`='%d', `wsd`='%d', `wtsd`='%d', `fold`='%s', `created`='%d', `sb`='%d', `bb`='%d'",
    --        table_name, lid, mid, rid, seatid, win, chipin, cards, fee, seat_chips, user_chips, tid, is_win, is_vpip, pfr, wsd, wtsd, fold, g.time(), sb, bb)
    --g.sendMysql(sql)
    g.sendRabbitQueue(msg, self.queue_name)


    return true

end

--取当前准备开始的比赛房间
function M:getMatchRooms()
    --local sql = string.format("select * from texas_match where status<2 and end_time=0")
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data
    --end
    --return {}

    local key = self:getRedisKey(self.key_texas_mtt_match)
    if not key then
        return
    end

    local res = g.callRedis("hgetall", key)
    if not res then
        return
    end
    local data = redis_to_table(res)
    --g.log:info("getMatchRooms:", data)

    for k, v in pairs(data) do
        local d = cjson.decode(v)
        local id = string.match(k, ":(%d+)")
        d.id = tonumber(id)
        local md = self:getMatchRoom(d.id)
        for k, v in pairs(d) do
            md[k] = v
        end
        data[k] = md
    end

    --g.log:info("getMatchRooms:", data)
    return data
end

--比赛场报名信息
function M:getMatchRoomSignMids(rid)
    --local sql = string.format("select * from texas_match_sign_up where status=1 and rid=%d", rid)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data
    --end
    --return {}

    local key = self:getRedisKey(self.key_texas_match_sign_up, rid)
    local res = g.callRedis("smembers", key)
    for k, v in pairs(res) do
        res[k] = tonumber(v)
    end
    g.log:debug("getMatchRoomSignMids:", res)
    return res

end

--机器人报名(改为了web_proxy
function M:robotMatchRoomSign(rid, mid)
    --local status = 1
    --local sql = string.format("insert into texas_match_sign_up (rid, mid, status, is_robot, create_time) values('%s', '%s', '%s', 1, '%s') on duplicate key update status=%s", rid, mid, status, g.time(), status)
    --g.sendMysql(sql)

    --local key = self:getRedisKey("sign:mtt", rid)
    --g.sendRedis("sadd", key, mid)

end

--增加比赛的机器人数
function M:updateMatchRoomSignCount(rid)
    --local sql = string.format("update texas_match set `sign_count` = `sign_count`+1 where id='%s'", rid)
    --g.sendMysql(sql)
end

--比赛场积分增加
function M:addMatchTodayScore(uid, score)
    --local sql = string.format("INSERT INTO texas_score (mid, score, today_score) VALUES ('%s', '%s', '%s')  ON DUPLICATE KEY UPDATE score=score+'%d', today_score='%s' ", uid, score, score, score, score)
    --g.sendMysql(sql)

    --local key = "mtt:score:".. uid
    --g.sendRedis("hincrby", key, "score", score)
    --g.sendRedis("hset", key, "today_score", score)
end

--清0当天积分
function M:clearMatchTodayScore(uid)
    --local sql = string.format("update texas_score set today_score=%s", 0)
    --g.sendMysql(sql)

    --local key = "mtt:score:".. uid
    --g.sendRedis("hset", key, "today_score", 0)
end

--取当前普通场房间
function M:getNormalRooms()
    --local sql = string.format("select * from texas_room_group")
    --local data = g.callMysql(sql)
    ----print("data_proxy getNormalRooms:", tostring(data))
    --if data and next(data) then
    --    return data
    --end
    --return {}

    local tb = require("config.texas_room_group")
    return tb

end

--重置机器人状态
function M:resetBots(table_name)
    if not table_name then return end
    --local sql = string.format("update `%s` set `running` = '0'", table_name)
    --g.sendMysql(sql)
end

--取机器人信息
function M:getBots(table_name)
    if not table_name then return end
    --local sql = string.format("SELECT * FROM `%s`", table_name)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data
    --end
end

--更新机器人状态
function M:updateBotStatus(table_name, rid, mid, tid)
    if not table_name then return end
    --tid = tid or ""
    --local sql = string.format("update texas_bot_info set `running`='%s', `tid`='%s' where `mid`=%s", rid, tid, mid)
    --g.sendMysql(sql)
end

--取最好牌
function M:getBestCards(uid)
    --local sql = string.format("SELECT `best_card` FROM member_card_info where mid='%s'", uid)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data[1].best_card
    --end

    local key = self:getRedisKey(self.key_member_card_info, uid)
    local res = g.callRedis("hget", key, "best_card")
    if not res then
        return
    end
    return res

end

--取最好牌,牌值
function M:getBestCardValue(mid)
    --local sql = string.format("SELECT `best_card_rank` FROM member_card_info where mid='%s'", mid)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data[1].best_card_rank
    --end

    local key = self:getRedisKey(self.key_member_card_info, uid)
    local res = g.callRedis("hget", key, "best_card_rank")
    if not res then
        return
    end
    return res
end

--更新最好牌型记录
function M:updateBestCards(msg)
    local mid = msg.mid
    local best_card = msg.best_cards
    local best_card_info = msg.info
    local best_card_rank = msg.rank

    --local sql = string.format("insert into member_card_info (`mid`, `best_card`, `best_card_info`, `best_card_rank`) values('%s', '%s', '%s', '%s') on duplicate key update `best_card`='%s', "..
    --        "`best_card_info`='%s', `best_card_rank`='%s' ",mid, best_card, info, rank, best_card, best_card_info, best_card_rank)
    --
    --g.sendMysql(sql)

    local key = self:getRedisKey(self.key_member_card_info, mid)
    g.callRedis("hset", key, "best_card", best_card)
    g.callRedis("hset", key, "best_card_info", best_card_info)
    g.callRedis("hset", key, "best_card_rank", best_card_rank)
    return true
end

--牌局记录
function M:setLogsDeskDetail(msg)
    --local fee = msg.fee
    --local detail = msg.detail
    --local created = msg.created
    --local tid = msg.tid
    --local rid = msg.rid
    --local ended = msg.ended
    --local curr = msg.curr
    --local lid = msg.lid
    --local sql = string.format("insert into texas_logs_table_detail (`rid`, `fee`, `detail`, `created`, `tid`, `ended`, `curr`, `lid`)"..
    --        " values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", rid, fee, detail, created, tid, ended, curr, lid)
    --g.sendMysql(sql)

    g.sendRabbitQueue(msg, self.queue_name)
    self:setLogsTable(msg)

    return true
end


--节点在线人数
function M:setLogsServer(msg)
    local sid = msg.sid
    local online = msg.online
    local play = msg.play
    local created = msg.created
    local bot_online = msg.bot_online or 0
    local bot_play = msg.bot_play or 0
    local gid = msg.gid
    --local sql = string.format("insert into server_logs_online_v2 (`gid`, `created`, `online`, `play`, `bot_online`, `bot_play`, `sid`)"..
    --        " values('%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
    --        gid, created, online, play, bot_online, bot_play, sid)
    --g.sendMysql(sql)
    local date = os.date("%Y%m%d", g.time())
    local hour = get_hour_num(g.time())
    local key = "online_user_num:"..date
    g.sendRedis("hset", key, hour, cjson.encode(msg))
end

--比赛场玩家信息
function M:setMatchUser(msg)
    local rank = msg.rank
    local award = msg.award
    local chip = msg.chip
    local start_time = msg.start_time
    local end_time = msg.end_time or 0
    local tid = msg.tid
    local mid = msg.mid
    local rid = msg.rid
    --local sql = string.format("insert into texas_match_room_user (`rank`, `award`, `chip`, `start_time`, `end_time`, `tid`, `mid`, `rid`)"..
    --        " values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') on duplicate key update `rank`='%s',`award`='%s',`chip`='%s',`start_time`='%s',`end_time`='%s',`tid`='%s' ",
    --        rank, award, chip, start_time, end_time, tid, mid, rid, rank, award, chip, start_time, end_time, tid)
    ----g.log:debug("sql:", sql)
    --g.sendMysql(sql)
    local key = "mtt:"..rid..":"..tid..":"..mid
    g.callRedis("hset", key, "rank", rank, "award", award, "chip", chip, "start_time", start_time, "end_time", end_time, "tid", tid, "mid", mid, "rid", rid)
    g.log:debug("setMatchUser", key, rank, chip)
end

--清空房间里的玩家信息
function M:clearMatchUser(rid, tid, mid)
    if not mid then return end
    local key = "mtt:"..rid..":"..tid..":"..mid
    g.callRedis("del", key)
    g.log:debug("clearMatchUser", key)
end

--登出日志
function M:setLogsLogout(msg)
    --local mid = msg.mid
    --local login_time = msg.login_time
    --local logout_time = msg.logout_time
    --local normal_round = msg.normal_round
    --local match_round = msg.match_round
    --local sql = string.format("insert into logs_login (`mid`, `login_time`, `logout_time`, `normal_round`, `match_round`)"..
    --        " values('%s', '%s', '%s', '%s', '%s') ",
    --        mid, login_time, logout_time, normal_round, match_round)
    ----g.log:debug("sql:", sql)
    --g.sendMysql(sql)

    local cur_info = {
        normal_round = 0,
        match_round = 0,
        online_time = 0,
    }
    local res = g.dp:getLogsLogout(msg)
    if res then
        for k, v in pairs(res) do
            cur_info[k] = v
        end
    end
    msg.info.online_time = msg.info.online_time + cur_info.online_time
    msg.info.match_round = msg.info.match_round + cur_info.match_round
    msg.info.normal_round = msg.info.normal_round + cur_info.normal_round

    local key = "online_time:"..msg.date
    g.sendRedis("hset", key, msg.uid, cjson.encode(msg.info))
    g.sendRedis("expire", key, g.const.redis_time.default_exprie)

end

function M:getLogsLogout(msg)
    local key = "online_time:"..msg.date
    local res = g.callRedis("hget", key, msg.uid)
    if not res then
        return
    end
    res = cjson.decode(res)
    return res
end

--机器人从金币池中取出金币
function M:getBotChipsPool()
    --local sql = "select * from texas_bot_chips_pool"
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data[1]
    --end
    --return nil
    local key = "robot_chip_pool"
    local res = g.callRedis("get", key)
    if not res then
        return 0
    end
    return tonumber(res)
end

--更新金币池金币
function M:updateBotChipsPool(chips)
    --if not id then id = 1 end
    --local t = g.time()
    --local sql = string.format("update texas_bot_chips_pool set `chips`= `chips`+'%d', `ltime`='%s' where id='%s'", chips, t , id)
    --g.sendMysql(sql)

    local key = "robot_chip_pool"
    local res = g.callRedis("INCRBYFLOAT", key, chips)
    if not res then
        return 0
    end
    return true
end

--取房间jackpot
function M:getJackpot(rid)
    --local sql = string.format("select * from texas_room_group where id='%s' limit 1", rid)
    --local data = g.callMysql(sql)
    --if data and next(data) then
    --    return data[1].jackpot or 0
    --end
    --return nil

    local key = self:getRedisKey(self.key_texas_jackpot, rid)
    local res = g.callRedis("get", key)
    if not res then
        return
    end
    return res
end

--更新房间jackpot
function M:updateJackpot(rid, num)
    --local sql = string.format("update texas_room_group set jackpot=jackpot+'%d' where id='%d' limit 1", num, rid)
    --g.sendMysql(sql)
    --return true

    local key = self:getRedisKey(self.key_texas_jackpot, rid)
    local res = g.callRedis("incrbyfloat", key, num)
    if not res then
        return
    end
    return res
end

--jackpot中奖记录
function M:setLogsJackpot(msg)
    --local rid = msg.rid
    --local result = msg.result
    --local change = msg.change
    --local time = msg.time
    --local info = msg.info
    --local award_kind = msg.award_kind or 0
    --local sql = string.format("insert into logs_jackpot (`rid`, `result`, `change`, `time`, `info`, `award_kind`) "..
    --    "values('%s', '%s', '%s', '%s', '%s', '%s')", rid, result, change, time, info, award_kind)
    --g.sendMysql(sql)

    g.sendRabbitQueue(msg, self.queue_name)
    return true
end


--比赛积分记录
function M:setLogsMatchScore(msg)
    --local rid = msg.rid
    --local user_score = msg.user_score
    --local time = msg.time
    --local create_mid = msg.create_mid
    --local sql = string.format("insert into logs_match_score (`rid`, `user_score`, `time`, `create_mid`) "..
    --        "values('%s', '%s', '%s', '%s')", rid, user_score, time, create_mid)
    --g.sendMysql(sql)

    g.sendRabbitQueue(msg, self.queue_name)

    return true
end

function M:setTexasMatchEnd(msg)
    g.sendRabbitQueue(msg, "unsign_mtt")
    --g.sendRabbitQueue(msg, self.queue_name)
end

--桌子输赢记录
function M:setLogsTable(msg)
    local key = "logs_table:"..msg.tid
    --local key2 = "logs_table:"..msg.tid .. ":2"
    --local ex_time = g.const.redis_time.default_exprie

    local data = cjson.encode(msg)

    --g.sendRedis("rpush", key,  data)

    --local len = g.callRedis("llen", key)
    --if len > 300 then
    --    g.sendRedis("rtrim", key,  -200, -1) --最多300条记录
    --end
    --
    --local key2 = "logs_table_num"
    --local ex = g.const.redis_ex.common
    --g.sendRedis("hincr", key2, msg.tid, 1)
    --g.sendRedis("expire", key2, ex)
    self.logs_table_num = self.logs_table_num + 1
    g.sendRedis("zadd", key, self.logs_table_num, data)
    local max_size = 300
    local size = g.callRedis("zcard", key)
    if size > max_size then
        g.sendRedis("zremrangebyrank", key, 0, size-max_size-1)
    end
    g.sendRedis("expire", key, g.const.redis_ex.one_hour)
    --g.log:debug("setLogsTable:", key, size, self.logs_table_num)
end

function M:delLogsTable(tid)
    local key = "logs_table:"..tid
    g.sendRedis("del", key)
end

function M:delLogsTables(str)
    local key = "logs_table:" .. str
    local tb = g.callRedis("keys", key)
    g.log:debug("delLogsTables", tb)
    for k, v in pairs(tb) do
        g.sendRedis("del", v)
    end
end

function M:isExistsKey(key)
    return g.callRedis("exists", key)
end

function M:isExitsRobot(id)
    local key = self:getRedisKey(self.m_info_key_mid, id)
    return self:isExistsKey(key)
end

--比赛场上的桌子
function M:setMttTid(rid, tid)
    local key = "mtt:"..rid .. ":tid"
    --g.sendRedis("hset", key, tid, 1)
    g.sendRedis("lpush", key,  tid)
end


function M:getSNRoomConfig()
    local tb = require("config.sn_room_cfg")
    return tb
end

return M